<?php
/**
 Plugin Name: Twitter Fans (Like Box for Twitter)
 Plugin URI: http://sohailabid.com/projects/twitter-fans/
 Version: 3.0
 Description: Display your Twitter followers in the sidebar (or anywhere in the theme) just like Faebook's Like Box
 Author: Sohail Abid
 Author URI: http://sohailabid.com
 */

class Twitter_Fans_Widget extends WP_Widget
{
	function __construct() {
		parent::WP_Widget('twitter_fans', 'Twitter Fans (Like Box for Twitter)', array('description' => 'Display your Twitter followers in the sidebar just like Facebook\'s Like Box'));
	}
	
	function widget($args, $instance)
	{
		$username = $instance['username'];
		$number   = $instance['number'];	
	
		//echo $args['before_widget'];
		echo get_twitter_like_box($username, $number);
		//echo $args['after_widget'];
	}
	
	function form($instance)
	{
		$instance = wp_parse_args( (array) $instance, array( 'username' => 'SohailAbid', 'number' => '8' ) );
		$username = strip_tags($instance['username']);
		$number   = strip_tags($instance['number']);
		?>
		<p><label for="<?php echo $this->get_field_id('username'); ?>">Username: <input class="widefat" id="<?php echo $this->get_field_id('username'); ?>" name="<?php echo $this->get_field_name('username'); ?>" type="text" value="<?php echo esc_attr($username); ?>" /></label></p>
		<p><label for="<?php echo $this->get_field_id('number'); ?>">How many followers to show: <input class="widefat" id="<?php echo $this->get_field_id('number'); ?>" name="<?php echo $this->get_field_name('number'); ?>" type="text" value="<?php echo esc_attr($number); ?>" /></label></p>
		<?php
	}

	function update( $new_instance, $old_instance )
	{
		$instance = array();
		$instance['username'] = strip_tags( $new_instance['username'] );
		$instance['number'] = strip_tags( $new_instance['number'] );
		
		//fetch_twitter_followers($instance['username'], $instance['number']);
		
		return $instance;
	}
}

add_action('widgets_init', create_function( '', 'register_widget("Twitter_Fans_Widget");' ) );

function get_twitter_like_box($username, $number)
{
	$twitter = get_option("twitter_fans");
	
	if(!$twitter[$username])
	{
		//fetch_twitter_followers($username, $number);
		$twitter = get_option("twitter_fans");
	}
	
	$twitter = $twitter[$username];
 //echo '<pre>'; print_r($twitter['you']); echo '</pre>';
 
	$return  = '<div style="border:1px solid #AAA; border-top-color:#315C99; margin-bottom:15px; padding:5px 5px 0 5px; font-family:\'Lucida grande\',tahoma,verdana,arial,sans-serif;">';
		$return .= '<div style="color:#555;border-bottom:1px solid #D8DFEA;color:#555; height:60px; position:relative;">';
			$return .= '<div style="position:absolute;top:5px;left:5px;"><a target="_blank" href="http://twitter.com/' . $twitter['you'][0]->screen_name . '"><img src="' . $twitter['you'][0]->profile_image_url . '" width="44" height="44"></a></div>';
			$return .= '<div style="position:absolute;top:5px;left:59px;font-size:14px;line-height:14px;font-weight:bold;"><a target="_blank" href="http://twitter.com/'.$twitter['you'][0]->screen_name.'" style="color:#3B5998">' . $twitter['you'][0]->screen_name . '<span style="font-weight:normal;font-size:10px"> on Twitter</span></a></div>';
			$return .= '<div style="position:absolute;top:30px;left:59px;"><a href="https://twitter.com/'.$twitter['you']['screen_name'].'" class="twitter-follow-button" data-show-count="false" data-width="65px" data-show-screen-name="false">Follow @'.$twitter['you']['screen_name'].'</a></div>';
		$return .= '</div>';
		$return .= '<div style="background:#FFF;padding:0;">';
		$return .= '<div style="background:#FFF;padding:5px 5px 0px 5px;font-size:11px;">'.$twitter['you'][0]->followers_count.' people follow <strong>'.$twitter['you'][0]->screen_name.'</strong></div>';
		if ( $twitter['followers'])
    {
    for($i=0; $i < $number; $i++)
			{
				$return .= '<span style="line-height:1;padding:5px 4px 8px 5px;width:48px;float:left"><a target="_blank" href="http://twitter.com/'.$twitter['followers'][$i]['screen_name'].'" style="color:gray"><img src="'.$twitter['followers'][$i]['profile_image_url'].'" width="48" height="48"><span style="font-family:Arial;font-size:10px;">'.substr($twitter['followers'][$i]['screen_name'], 0, 8).'</a></span>';
			}
    }
		$return .= '<br style="clear:both"></div>';
	$return .= '</div>';
	$return .= '<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>';
	
	return $return;
}

function twitter_like_box($username = 'SohailAbid', $number = 8)
{
	echo get_twitter_like_box($username, $number);
}

function fetch_twitter_followers($username = 'SohailAbid')
{
	$you 						= twitter_fans_get_json("http://api.twitter.com/1/users/lookup.json?screen_name=$username");
	$you['name'] 			 	= (string)$you[0]->name;
	$you['screen_name']	 		= (string)$you[0]->screen_name;
	$you['followers_count'] 	= (string)$you[0]->followers_count;
	$you['profile_image_url']	= (string)$you[0]->profile_image_url;

	$fans = twitter_fans_get_json("http://api.twitter.com/1/followers/ids.json?screen_name=$username");
	$fans_ids = (string)implode( ',', array_slice($fans->ids, 0, 25) );
	$fans = twitter_fans_get_json("http://api.twitter.com/1/users/lookup.json?user_id=$fans_ids");
	
	$followers = array();
    for($i=0; $i < 25; $i++)
    {
        $followers[$i]['screen_name'] 		= (string)$fans[$i]->screen_name;
        $followers[$i]['profile_image_url'] = (string)$fans[$i]->profile_image_url;
    }
	
	$twitter_fans = array();
	$twitter_fans['you'] = $you;
	$twitter_fans['followers'] = $followers;

	$twitter_fans_all = get_option("twitter_fans");
	$twitter_fans_all[$username] = $twitter_fans;
	
	delete_option("twitter_fans");
	update_option("twitter_fans", $twitter_fans_all);
}

/*******************************************
*  WP-CRON
********************************************/

if (!wp_next_scheduled('twitter_fans_cron')) {
	wp_schedule_event( time(), 'daily', 'twitter_fans_cron' );
}

add_action( 'twitter_fans_cron', 'twitter_fans_cron' );

function twitter_fans_cron() {
	$twitter_fans_all = get_option("twitter_fans");
	
	foreach($twitter_fans_all as $username => $twitter_fans_one)
	{
		fetch_twitter_followers($username);
	}
}


/*******************************************
*  UTILITY FUNCTIONS
********************************************/

function twitter_fans_get_json($url)
{
	if (function_exists("curl_init"))
		$data = @twitter_fans_curl_get_contents($url);
	else
		$data = @file_get_contents($url);
	
	if(function_exists("json_decode"))
		$data = json_decode($data);
	else
		$data = twitter_fans_json_decode($data);
	
	return $data;
}

function twitter_fans_curl_get_contents($url)
{
    $ch = curl_init();
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_HEADER, 0);
    ob_start();
    curl_exec ($ch);
    curl_close ($ch);
    $return = ob_get_contents();
    ob_end_clean();
    return $return;    
}

function twitter_fans_json_encode($value)
{
	$json = new Services_JSON();
	return $json->encode($value);
}

function twitter_fans_json_decode($value)
{
	$json = new Services_JSON();
	return $json->decode($value);
}